package com.mike.median.util;

public class CalculateUtils {
    public static double findMedianArrays(Integer[] A, Integer[] B) {
        int N1 = A.length;
        int N2 = B.length;

        if (N1 < N2) return findMedianArrays(B, A);
        if (N2 == 0)
            return ((double) A[(N1 - 1) / 2] + A[N1 / 2]) / 2;
        int a = 0, b = N2 * 2;
        while (true) {
            int mid2 = (a + b) / 2;
            int mid1 = N1 + N2 - mid2;

            double AL = (mid1 == 0) ? Integer.MIN_VALUE : A[(mid1 - 1) / 2];
            double BL = (mid2 == 0) ? Integer.MIN_VALUE : B[(mid2 - 1) / 2];
            double AR = (mid1 == N1 * 2) ? Integer.MAX_VALUE : A[(mid1) / 2];
            double BR = (mid2 == N2 * 2) ? Integer.MAX_VALUE : B[(mid2) / 2];

            if (AL > BR) a = mid2 + 1;
            else if (BL > AR) b = mid2 - 1;
            else return (Math.max(AL, BL) + Math.min(AR, BR)) / 2;
        }

    }

    public static Integer[] tansToIntArray(String str) {
        String[] transTmp = str.split(",");
        Integer[] result = new Integer[transTmp.length];
        for (int i = 0; i < transTmp.length; i++) {
            result[i] = Integer.valueOf(transTmp[i].trim());
        }
        return result;
    }
}
